//
// Created by hy on 2018/8/18.
//

#include <cstring>
#include "HiTime.h"
#include <sys/time.h>

void HiTime::start() {
    gettimeofday(&m_preTime, NULL);
    m_started = true;
}

void HiTime::restart() {
    this->start();
}

uint64_t HiTime::elapsed_ms() const {
    if (m_started)
    {
        timeval tv;
        gettimeofday(&tv, NULL);
        timersub(&tv, &m_preTime,  &tv);
        return static_cast<uint64_t>(tv.tv_sec * 1000 + tv.tv_usec / 1000);
    }
    return 0;
}

uint64_t HiTime::elapsed_us() const {
    if (m_started)
    {
        timeval tv;
        gettimeofday(&tv, NULL);
        timersub(&tv, &m_preTime,  &tv);
        return static_cast<uint64_t>(tv.tv_sec * 1000 * 1000 + tv.tv_usec);
    }
    return 0;
}

uint64_t HiTime::elapsed_s() const {
    if (m_started)
    {
        timeval tv;
        gettimeofday(&tv, NULL);
        timersub(&tv, &m_preTime,  &tv);
        return static_cast<uint64_t>(tv.tv_sec);
    }
    return 0;
}

HiTime::HiTime()
{
    m_started = false;
}

void HiTime::stop() {
    m_started = false;
}

bool HiTime::started() {
    return m_started;
}


